﻿using System;
using System.IO;
using System.Text;

namespace VPLink2013.Framework
{
    /// <summary>
    /// This class writes a trace/log file
    /// </summary>
    public static class ContextTrace
    {
        private static StringBuilder sb;
        public static string PathTemp = string.Empty;
        public static string PrefixFileName = string.Empty;

        public static void AddTrace(string message)
        {
            sb = sb ?? new StringBuilder();
            sb.AppendLine( message);
        }

        /// <summary>
        /// Add a message
        /// </summary>
        /// <param name="message"></param>
        public static void AddTrace(string message,DateTime dtTrace, DateTime dtDateDebutProcess )
        {
            sb = sb ?? new StringBuilder();

            TimeSpan tsTrace = DateTime.Now - dtTrace;
            TimeSpan tsTraceTotal = DateTime.Now - dtDateDebutProcess;
            sb.AppendLine(tsTrace.TotalMilliseconds.ToString("0000 ")
                + tsTraceTotal.TotalMilliseconds.ToString("0000 ")
                + message);
            dtTrace = DateTime.Now;
        }

        /// <summary>
        /// Save the trace (log) file
        /// </summary>
        public static string Save(string PathTemp, string PrefixFileName )
        {
            try
            {
                EnsureFolderExist(PathTemp);
                string strPath = string.Format(@"{0}\{1}.txt", PathTemp, PrefixFileName);
                File.WriteAllText(strPath, sb.ToString());
            }
            catch (System.Exception)
            {
                //return "Error.ContextTrace.Save : " + exc.Message + "/" + exc.StackTrace;
            }
            return string.Empty;
        }


        public static void EnsureFolderExist(string PathLog)
        {
            EnsureFolderExist(PathLog, 1);
        }
        private static void EnsureFolderExist(string PathLog, int Level)
        {
            if (Directory.Exists(PathLog) || Level > 20)
            {
                return;
            }

            try
            {
                if (!Directory.Exists(PathLog))
                {
                    string Temp = PathLog.Substring(0, PathLog.LastIndexOf(@"\"));
                    if (Directory.Exists(Temp))
                    {
                        Directory.CreateDirectory(PathLog);
                    }
                    else
                    {
                        EnsureFolderExist(Temp, Level + 1);
                    }
                    EnsureFolderExist(PathLog, Level + 1);
                }
            }
            catch (System.Exception)
            {
                return;
            }
        }
    }
}
